package servlet;

import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Arrays;

/**
 * @author 石小俊
 * @date 2023年06月30日 10:30
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/showAddEmp.emp":
                showAddEmp(request, response);
                break;
            case "/addEmp.emp":
                addEmp(request, response);
                break;
            case "/showModifyEmp.emp":
                showModifyEmp(request, response);
                break;
            case "/modifyEmp.emp":
                modifyEmp(request, response);
                break;
            case "/findAll.emp":
                findAll(request, response);
                break;
            case "/deleteEmp.emp":
                deleteEmp(request, response);
                break;
            default:
                PrintWriter out = response.getWriter();
                out.println("<h1 style='color:red;'>您输入的请求尚未处理,请检查请求是否正确<h1>");
                break;
        }

    }

    public void showAddEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(" <!DOCTYPE html> ");
        out.println(" <html lang=\"en\"> ");
        out.println(" <head> ");
        out.println("     <meta charset=\"UTF-8\"> ");
        out.println("     <title>添加员工</title> ");
        out.println(" </head> ");
        out.println(" <body> ");
        out.println(" <h1>添加员工信息</h1> ");
        out.println(" <a href=\"findAll.emp\">返回员工列表</a> ");
        out.println(" <hr> ");
        // 在Servlet中绘制页面时存在表单
        // 表单提交可以提交到另一个Servlet
        // 在另一个Servlet中实现对应的功能
        out.println(" <form action=\"addEmp.emp\" method=\"get\"> ");
        out.println("     姓名:<input type=\"text\" name=\"name\"><br> ");
        out.println("     工资:<input type=\"text\" name=\"salary\"><br> ");
        out.println("     性别:<input type=\"radio\" name=\"gender\" value=\"man\">男 ");
        out.println("     <input type=\"radio\" name=\"gender\" value=\"woman\">女<br> ");
        out.println("     学历: ");
        out.println("     <select name=\"edu\"> ");
        out.println("         <option value=\"-1\">请选择</option> ");
        out.println("         <option value=\"1\">高中</option> ");
        out.println("         <option value=\"2\">大专</option> ");
        out.println("         <option value=\"3\">本科</option> ");
        out.println("         <option value=\"4\">研究生</option> ");
        out.println("     </select><br> ");
        out.println("     兴趣: ");
        out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"eat\">吃饭 ");
        out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"sleep\">睡觉 ");
        out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"beat\">打豆豆<br> ");
        out.println("     <input type=\"submit\" value=\"添加\"> ");
        out.println(" </form> ");
        out.println(" </body> ");
        out.println(" </html> ");
    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        // 1.根据该页面创建对应的表t_emp
        // 2.根据获取到的数据执行JDBC的添加操作
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp ")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("   (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));

             ps.executeUpdate();
            response.sendRedirect("findAll.emp");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            out.println("<h1 style='color:red;'>对不起,添加失败,失败原因:" + e.getMessage() + "</h1>");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("<h1 style='color:red;'>对不起,添加失败,失败原因:" + e.getMessage() + "</h1>");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void showModifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        System.out.println("id:" + id);
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                out.println(" <!DOCTYPE html> ");
                out.println(" <html lang=\"en\"> ");
                out.println(" <head> ");
                out.println("     <meta charset=\"UTF-8\"> ");
                out.println("     <title>修改员工</title> ");
                out.println(" </head> ");
                out.println(" <body> ");
                out.println(" <h1>修改员工信息</h1> ");
                out.println(" <a href=\"findAll.emp\">返回员工列表</a> ");
                out.println(" <hr> ");
                out.println(" <form action=\"modifyEmp.emp\" method=\"post\"> ");
                out.println("     编号:<input type=\"text\" name=\"id\" value=\"" + rs.getInt("id") + "\" readonly><br> ");
                out.println("     姓名:<input type=\"text\" name=\"name\" value=\"" + rs.getString("name") + "\"><br> ");
                out.println("     工资:<input type=\"text\" name=\"salary\" value=\"" + rs.getDouble("salary") + "\"><br> ");
                out.println("     性别:<input type=\"radio\" name=\"gender\" value=\"man\" " + (rs.getString("gender").equals("man") ? "checked" : "") + ">男 ");
                out.println("     <input type=\"radio\" name=\"gender\" value=\"woman\" " + (rs.getString("gender").equals("woman") ? "checked" : "") + ">女<br> ");
                out.println("     学历: ");
                out.println("     <select name=\"edu\"> ");
                out.println("         <option value=\"-1\">请选择</option> ");
                out.println("         <option value=\"1\" " + (rs.getString("edu").equals("1") ? "selected" : "") + ">高中</option> ");
                out.println("         <option value=\"2\" " + (rs.getString("edu").equals("2") ? "selected" : "") + ">大专</option> ");
                out.println("         <option value=\"3\" " + (rs.getString("edu").equals("3") ? "selected" : "") + ">本科</option> ");
                out.println("         <option value=\"4\" " + (rs.getString("edu").equals("4") ? "selected" : "") + ">研究生</option> ");
                out.println("     </select><br> ");
                out.println("     兴趣: ");
                out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"eat\" " + StringUtil.checkHobby(rs.getString("hobbies"), "eat") + ">吃饭 ");
                out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"sleep\" " + StringUtil.checkHobby(rs.getString("hobbies"), "sleep") + ">睡觉 ");
                out.println("     <input type=\"checkbox\" name=\"hobbies\" value=\"beat\" " + StringUtil.checkHobby(rs.getString("hobbies"), "beat") + ">打豆豆<br> ");
                out.println("     <input type=\"submit\" value=\"修改\"> ");
                out.println(" </form> ");
                out.println(" </body> ");
                out.println(" </html> ");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));
            ps.executeUpdate();

            response.sendRedirect("findAll.emp");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(" <!DOCTYPE html> ");
        out.println(" <html lang=\"en\"> ");
        out.println(" <head> ");
        out.println("     <meta charset=\"UTF-8\"> ");
        out.println("     <title>员工列表</title> ");
        out.println(" </head> ");
        out.println(" <body> ");
        out.println(" <h1>员工列表</h1> ");
        out.println(" <a href=\"showAddEmp.emp\">添加员工</a> ");
        out.println(" <hr> ");
        out.println(" <table border=\"1\"> ");
        out.println("     <tr> ");
        out.println("         <td>编号</td> ");
        out.println("         <td>姓名</td> ");
        out.println("         <td>工资</td> ");
        out.println("         <td>操作</td> ");
        out.println("     </tr> ");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            // 使用JDBC查询数据库中所有的员工信息
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                // 每一行数据对应表格的一行内容
                out.println("     <tr> ");
                out.println("         <td>" + rs.getInt("id") + "</td> ");
                out.println("         <td>" + rs.getString("name") + "</td> ");
                out.println("         <td>" + rs.getDouble("salary") + "</td> ");
                out.println("         <td> ");
                out.println("             <a href=\"showModifyEmp.emp?id=" + rs.getInt("id") + "\">修改</a> ");
                out.println("             <a href=\"deleteEmp.emp?id=" + rs.getInt("id") + "\" onclick=\"return confirm('是否确认删除')\">删除</a> ");
                out.println("         </td> ");
                out.println("     </tr> ");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        out.println(" </table> ");
        out.println(" </body> ");
        out.println(" </html> ");
    }

    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));

            ps.executeUpdate();

            response.sendRedirect("findAll.emp");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
